'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/imgs/kh/uploadmz 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			_id,
			url
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		console.log("userInfo======", userInfo);

		let ma_app_id = "ttdd4eabf3427ff08301"

		let A = await vk.baseDao.selects({
			dbName: "a_appid",
			// 主表where条件
			whereJson: {
				appid: ma_app_id
			},
		});

		console.log("A========", A);
		if (A.total == 0) {
			res = {
				code: 1,
				msg: "小程序appid错误"
			}
			return res
		}


		let appsecret = A.rows[0].appsecret


		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: ma_app_id, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})

		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token

		// 上传图片至内容库
		let urlT = "https://open.douyin.com/api/playlet/v2/resource/upload/"
		const tp = await uniCloud.httpclient.request(urlT, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				"access-token": access_token,
			},
			data: {
				resource_type: 2,
				ma_app_id: ma_app_id,
				image_meta: {
					url: url,
				},
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})
		console.log("tp", tp);

		// 图片信息同步至数据库中
		const num = await vk.baseDao.update({
			dbName: "vk-files",
			whereJson: {
				_id: _id
			},
			dataJson: {
				resource_type: tp.data.data.resource_type,
				open_pic_id: tp.data.data.image_result.open_pic_id
			}
		});

		console.log("num===", num);


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}